import { Notification } from 'element-ui'
import store from '@/store'
// <!--封装websocket对象-->
const FACE = {
  $ws: null, // webscoket实例
  temp: '',
  mathUserid: '',
  device_sn: '',
  wsUrl: 'wss://device.yiyanglao.com.cn:9010', // websocket链接地址
  // 初始化webSocket
  createWS: function (config) {
    const that = this
    FACE.mathUserid = config.mathUserid
    FACE.device_sn = config.device_sn
    try {
      if ('WebSocket' in window) {
        that.$ws = new WebSocket(that.wsUrl)
      } else if ('MozWebSocket' in window) {
        const MozWebSocket = window.MozWebSocket
        that.$ws = new MozWebSocket(that.wsURl)
      }
      that.$ws.onopen = that.wsOpen
      that.$ws.onmessage = that.wsMessage
      that.$ws.onerror = that.wsError
      that.$ws.onclose = that.wsClose
    } catch (e) {}
  },
  // <!--webSocket 打开-->
  wsOpen: function () {
    console.log('== websocket open == facewebsocket')
    store.dispatch('facewebsocket/setFiveBreakOff', true)
    // <!--开始心跳-->
    heartBeat.start()
    if (this.readyState == WebSocket.CONNECTING) {
      console.log('正在连接')
    } else if (this.readyState == WebSocket.CLOSING) {
      console.log('正在断开连接')
    } else if (this.readyState == WebSocket.OPEN) {
      let userinfo = localStorage.getItem("userdata") || {}
      const info = JSON.parse(userinfo);
      // const { info } = store.state.user
      let user_id = ''
      const mathUserid = FACE.mathUserid
      const device_sn = FACE.device_sn
      let data = {}
      if (info) {
        if (mathUserid) {
          user_id = info.id + '_' + mathUserid
        } else {
          user_id = info.id
        }
      }
      if (device_sn) {
        data = {
          cmd: 'bind_user',
          user_id: user_id,
          device_sn: device_sn
        }
        this.send(JSON.stringify(data))
      } else {
        Notification({
          title: '提示',
          message: '请先设置人员账号绑定人脸设备才能进行人脸识别',
          type: 'warning',
          duration: 5 * 1000
        })
      }
    } else if (this.readyState === WebSocket.CLOSED) {
      // 断开设置
    }
  },
  // <!--websocket 接收到服务器消息-->
  wsMessage: function (msg) {
    const data = JSON.parse(msg.data);
    if (data.route == 'heart_user') {
      // <!--接受到消息，重置心跳-->
      heartBeat.reset()
      store.dispatch('facewebsocket/setFiveBreakOff', true)
    } else if (data.route == 'error') {
      Notification({
        title: '提示',
        message: '请检查人脸设备是否未联网，或者未通电',
        type: 'warning',
        duration: 5 * 1000
      })
      store.dispatch('facewebsocket/setFiveBreakOff', false)
    } else {
      store.dispatch('facewebsocket/setFiveBreakOff', true)
      store.dispatch('facewebsocket/setSendFaceMsg', data)
    }
  },
  // <!--websocket 发生错误-->
  wsError: function (err) {
    heartBeat.close()
    store.dispatch('facewebsocket/setFiveBreakOff', false)
    console.log('== websocket error ==', err)
  },
  // <!--websocket 关闭连接-->
  wsClose: function (event) {
    console.log('长链接关闭')
    if (this.$ws) {
      this.$ws.close()
    }
    heartBeat.close()
    store.dispatch('facewebsocket/setFiveBreakOff', false)
  },
  // 处理报警信息
  init: function (res, _that) {

  }
}
// <!--webSocket 心跳-->
const heartBeat = {
  timeout: 60000, // 3分钟心跳重连时间
  timeoutObj: null, // 定时器
  reset: function () {
    clearInterval(this.timeoutObj)
    heartBeat.start()
  },
  // 关闭心跳
  close: function () {
    store.dispatch('facewebsocket/setFiveBreakOff', false)
    clearInterval(this.timeoutObj)
  },
  start: function () {
    this.timeoutObj = setTimeout(function () {
      if (FACE.$ws && FACE.$ws.readyState == 1) {
        const data = {
          cmd: 'heart_user'
        }
        store.dispatch('facewebsocket/setFiveBreakOff', false)
        FACE.$ws.send(JSON.stringify(data))
      }
    }, this.timeout)
  }
}
export default FACE
